package util;


import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.util.*;

public class VagueUtil<T> {
    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    public Specification<T> createSpecification(Map searchMap) {

        return new Specification<T>() {

            @Override
            public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // ID
                String key = null;
                Iterator it=searchMap.keySet().iterator();
                while (it.hasNext()) {
                    key=(String)it.next();
                    if(searchMap.get(key)!=null && !"null".equals(searchMap.get(key))){
                        if(searchMap.get(key).getClass().equals(HashSet.class)){
                            Path<Object> path = root.get(key);
                            CriteriaBuilder.In<Object> in = cb.in(path);
                            Set<String> id = (Set<String>) searchMap.get(key);
                            id.forEach(i -> in.value(i));
                            predicateList.add(in);
                        }else{
                        predicateList.add(cb.like(root.get(key).as(String.class), "%"+(String)searchMap.get(key)+"%"));
                        }
                    }
                }


                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
